using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using ActivateYourGlutes.Infrastructure;
using ActivateYourGlutes.Infrastructure.Logging;
using ActivateYourGlutes.Model.Providers;

namespace ActivateYourGlutes.Controllers
{
    public partial class ErrorLogController : LocalisingController
    {
        private readonly IErrorLogProvider _errorLogProvider;
        private const string FailedToDeleteMessage = "Error occurred during deletion of error log item with ID {0}.\nError message: {1}";

        public ErrorLogController(IAccountProvider accountProvider, IErrorLogProvider errorLogProvider, ILogger logger) : base(accountProvider, logger)
        {
            _errorLogProvider = errorLogProvider;
        }

        [RequireSsl]
        [Authorize(Roles = "Administrator")]
        public virtual ActionResult Index()
        {
            return View();
        }
         
        [RequireSsl]
        [Authorize(Roles = "Administrator")]
        public virtual ActionResult GridData(string sidx, string sord, int page, int rows)
        {
            var pageIndex = Convert.ToInt32(page) - 1;
            var pageSize = rows;
            var totalRecords = _errorLogProvider.TotalLogItems();
            var totalPages = (int)Math.Ceiling(totalRecords / (float)pageSize);
            var logItems = _errorLogProvider.LogItems(CurrentAccount, pageIndex * pageSize, pageSize);

            var jsonData = new
            {
                total = totalPages,
                page,
                records = totalRecords,
                rows = (
                    from item in logItems.ToArray()
                    select new
                    {
                        id = item.Id,
                        cell = new[] { "", item.FormattedErrorLevel, item.Timestamp.ToString(LocaleSettings.DateTimeFormat), item.HasExceptionDetails ? "Yes" : "No", item.Message }
                    }
                ).ToArray()
            };


            return Json(jsonData);
        }

        [RequireSsl]
        [Authorize(Roles="Administrator")]
        public virtual ActionResult Detail(int id)
        {
            try
            {
                ViewData.Model = _errorLogProvider.GetLogItemById(CurrentAccount, id);
                return View();
            }
            catch (AuthorizationException)
            {
                return this.RedirectToUnauthorized();
            }
        }

        [RequireSsl]
        [Authorize(Roles = "Administrator")]
        public virtual ActionResult Delete(int? id)
        {
            if (Request.IsAjaxRequest() && id != null)
            {
                try
                {
                    _errorLogProvider.Delete(CurrentAccount, id.Value);
                }
                catch (Exception ex)
                {
                    Logger.Warning(String.Format(FailedToDeleteMessage, id.Value, ex.Message));
                    return Json(false);
                }
                return Json(true);
            }
            return new EmptyResult();
        }

        [RequireSsl]
        [Authorize(Roles="Administrator")]
        public virtual ActionResult DeleteAll()
        {
            return View();
        }

        [RequireSsl]
        [Authorize(Roles="Administrator")]
        [AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult DeleteAll(string confirmation)
        {
            if (String.IsNullOrEmpty(confirmation))
                throw new ArgumentNullException("confirmation");
            if (confirmation.ToLower() == "yes")
            {
                try
                {
                    _errorLogProvider.Clear(CurrentAccount);
                }
                catch (AuthorizationException)
                {
                    return this.RedirectToUnauthorized();
                }
            }
            return RedirectToAction(MVC.ErrorLog.Index());
        }
    }
}
